package com.zbs.framework.dao.user.repository;

import com.zbs.framework.dao.role.entity.Role;
import com.zbs.framework.dao.user.entity.UserRole;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UserRoleRepository extends JpaRepository<UserRole, Long>, JpaSpecificationExecutor<UserRole> {

    /**
     * 根据用户ID删除
     * @param userId
     */
    void deleteAllByUserId(Long userId);

    /**
     * 删除用户绑定角色
     * @param roleId
     */
    void deleteAllByRoleId(Integer roleId);

    /**
     * 根据用户ID获取用户角色Id
     * @param userId
     * @return
     */
    @Query("select ur.roleId from UserRole ur where ur.userId = :userId")
    Integer[] findRoleIds(@Param("userId") Long userId);

    /**
     * 根据用户角色ID获取用户Id
     * @param roleId
     * @return
     */
    @Query("select ur.userId from UserRole ur where ur.roleId = :roleId")
    List<Long> findUserIds(@Param("roleId") Integer roleId);

    /**
     * 获取用户角色列表
     * @param userId
     * @return
     */
    @Query("select r from UserRole ur left join Role r on ur.roleId = r.id where ur.userId = :userId")
    List<Role> findUserRoles(@Param("userId") Long userId);

    /**
     * 根据角色ID判断是否存在
     * @param roleId
     * @return
     */
    boolean existsByRoleId(Integer roleId);
}
